package com.rongshu.view.home.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.rongshu.R;
import com.rongshu.view.home.entity.AiteListBean;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.listener.OnExpandFunctionListener;
import com.widget.CircleImageView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

public class CommentExpandableLinearLayout extends LinearLayout {

    //自定义属性
    //一开始展示的条目数
    private int defaultItemCount = 1;
    //展开
    private String expandText;//待展开显示的文字
    //隐藏
    private String hideText;//待隐藏显示的文字

    //item view
    private View view = null;
    private RelativeLayout layout_all;
    private RelativeLayout layout_head;
    private CircleImageView iv_head_icon;
    private ImageView iv_vip;
    private TextView txt_comment_people_name;
    private ExpandableTextView txt_comment_content;

    private boolean isExpand = false;//是否是展开状态，默认是隐藏
    //是否已经有底部，默认为false，没有
    private boolean hasBottom;
    //消息数
    private int count = 0;
    //bottom view
    private View bottomView;
    private TextView tvTip;
    //二级回复界面
    private List<CommentReplysBean> mCommentReplysBeanList = null;
    //interface
    private OnItemClickListener mOnItemClickListener = null;


    public CommentExpandableLinearLayout(Context context) {
        this(context, null);
    }

    public CommentExpandableLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
    }

    /**
     * 自定义属性
     *
     * @param attrs
     */
    private void initAttrs(AttributeSet attrs) {
        TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CommentExpandableLinearLayout, 0, 0);
        try {
            defaultItemCount = typedArray.getInt(R.styleable.CommentExpandableLinearLayout_comment_defaultItemCount, defaultItemCount);
            expandText = typedArray.getString(R.styleable.CommentExpandableLinearLayout_comment_expandText);
            hideText = typedArray.getString(R.styleable.CommentExpandableLinearLayout_comment_hideText);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            typedArray.recycle();
        }
        setOrientation(VERTICAL);
    }

    /**
     * 设置方向
     *
     * @param orientation
     */
    @Override
    public void setOrientation(int orientation) {
        if (LinearLayout.HORIZONTAL == orientation) {
            throw new IllegalArgumentException("ExpandableTextView only supports Vertical Orientation.");
        }
        super.setOrientation(orientation);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initBottomView();
    }

    private void initBottomView() {
        bottomView = View.inflate(getContext(), R.layout.item_ell_bottom, null);
        tvTip = bottomView.findViewById(R.id.tvTip);
        tvTip.setText(expandText);
        bottomView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int childCount = getChildCount();
        justToAddBottom(childCount);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    /**
     * 判断是否要添加底部
     */
    private void justToAddBottom(int childCount) {
        //判断是否要添加底部
        if (childCount > defaultItemCount || count > defaultItemCount) {
            if (!hasBottom) {
                addView(bottomView);//添加底部
                if (!isExpand) {
                    hide();
                } else {
                    expand();
                }
                hasBottom = true;
            }
        }
    }

    /**
     * 收起
     */
    private void hide() {
        int endIndex = getChildCount() - 1;
        for (int i = defaultItemCount; i < endIndex; i++) {
            //从默认显示条目位置以下的都隐藏
            View view = getChildAt(i);
            view.setVisibility(GONE);
        }
    }

    /**
     * 展开
     */
    private void expand() {
        for (int i = defaultItemCount; i < getChildCount(); i++) {
            //从默认显示条目位置以下的都显示出来
            View view = getChildAt(i);
            view.setVisibility(VISIBLE);
        }
    }

    /**
     * add view
     *
     * @param view
     */
    public void addItem(View view) {
        if (!hasBottom) {
            //如果还没有底部
            addView(view);
        } else {
            int childCount = getChildCount();
            addView(view, childCount - 1);//插在底部之前
        }

        refreshUI(view);
    }

    /**
     * 刷新UI
     *
     * @param view
     */
    private void refreshUI(View view) {
        int childCount = getChildCount();
        if (childCount > defaultItemCount) {
            if (childCount - defaultItemCount == 1) {
                //刚超过默认，判断是否要添加底部
                justToAddBottom(childCount);
            }
            if (!isExpand) {
                view.setVisibility(GONE);//大于默认数目的先隐藏
            } else {
                view.setVisibility(VISIBLE);//news
            }
        }
    }


    /**
     * 展开收缩
     */
    public void toggle() {
        if (isExpand) {
            hide();
            tvTip.setText(expandText);
        } else {
//            expand();
            tvTip.setText(hideText);
        }
        isExpand = !isExpand;

        //回调
        if (mStateListener != null) {
            mStateListener.onStateChanged(isExpand);
        }
    }

    /**
     * 设置数据
     */
    public void setCommentReplysBeanList(List<CommentReplysBean> list, int count) {
        if (list.isEmpty() || list == null) {
            return;
        }
        this.mCommentReplysBeanList = list;
        this.count = count;
        this.hasBottom = false;
        //清空所有数据
        removeAllViews();
        // add view
        for (int i = 0; i < mCommentReplysBeanList.size(); i++) {
            View view = getView(i);
            addItem(view);
        }
    }

    /**
     * 设置展开字体
     */
    public void setExpandText(String expandText) {
        this.expandText = expandText;
        tvTip.setText(expandText);
    }

    /**
     * 设置是否是展开或收缩
     */
    public void setIsExpand(boolean isExpand) {
        this.isExpand = isExpand;
    }

    /**
     * 返回当前状态
     */
    public boolean getIsExpand() {
        return this.isExpand;
    }

    /**
     * 设置view
     */
    public View getView(final int position) {
        try {
            view = LayoutInflater.from(getContext()).inflate(R.layout.comment_expandable_item_view, null, false);
            layout_all = view.findViewById(R.id.layout_all);
            layout_head = view.findViewById(R.id.layout_head);
            iv_head_icon = view.findViewById(R.id.iv_head_icon);
            iv_vip = view.findViewById(R.id.iv_vip);
            txt_comment_people_name = view.findViewById(R.id.txt_comment_people_name);
            txt_comment_content = view.findViewById(R.id.txt_comment_content);
            //data
            final CommentReplysBean commentReplysBean = mCommentReplysBeanList.get(position);
            //load icon
            RequestOptions options = new RequestOptions()
                    .placeholder(R.drawable.user_head_icon);
            Glide.with(getContext())
                    .load(commentReplysBean.getAvatar())
                    .apply(options)
                    .into(iv_head_icon);
            //vip
            iv_vip.setVisibility(commentReplysBean.isVip() ? VISIBLE : GONE);
            //name
            txt_comment_people_name.setText(commentReplysBean.getFrom_Name());
            //content
            //@集合
            List<AiteListBean> aiteListBean = commentReplysBean.getAiteList();
            //内容
            String content = null;
            content = commentReplysBean.getContents();
            content = content.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            content = URLDecoder.decode(content, "utf-8");
            //回复人
            String to_Name = commentReplysBean.getTo_Name();
            txt_comment_content.setAiteListBeanList(aiteListBean);
            if (!TextUtils.isEmpty(to_Name)) {
                String replyContent = "回复 " + to_Name + " ";
                txt_comment_content.setReply_content(replyContent);
            }
            txt_comment_content.setText(content);
            txt_comment_content.setOnExpandFunctionListener(new OnExpandFunctionListener() {
                @Override
                public void onClick() {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(position);
                    }
                }

                @Override
                public void onAtClick(int user_id) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemAtAndHeaderClick(user_id, (commentReplysBean.getIs_allow_browse_homepage() == 1));
                    }
                }
            });
            layout_head.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemAtAndHeaderClick(commentReplysBean.getFrom_uid(), (commentReplysBean.getIs_allow_browse_homepage() == 1));
                    }
                }
            });
            layout_all.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(position);
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return view;
    }

    private OnStateChangeListener mStateListener;

    /**
     * 定义状态改变接口
     */
    public interface OnStateChangeListener {
        void onStateChanged(boolean isExpanded);
    }

    public void setOnStateChangeListener(OnStateChangeListener mListener) {
        this.mStateListener = mListener;
    }

    public void setOnItemClickListener(final OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public interface OnItemClickListener {

        void onItemClick(int replyPosition);

        void onItemAtAndHeaderClick(int user_id, boolean is_allow_browse_homepage);
    }
}
